package org.oneblog.data.service.impl;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;

import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.oneblog.data.fields.ArticleField;
import org.oneblog.data.query.ArticleSolrQuery;
import org.oneblog.data.util.StringTools;

public class AbstractSolrService {

    protected String getHighLight(Map<String, Map<String, List<String>>> high, String key, String field, String oldTitle) throws Exception {
        String k = "";
        String rs = "";
        try {
            if (high != null && high.size() > 0 && high.get(key) != null) {
                k = high.get(key).get(field).get(0);
                if(StringUtils.isBlank(k)) {
                    return oldTitle;
                }
                Matcher m_script = StringTools.p_script.matcher(k);
                k = m_script.replaceAll("");
            } else {
                return oldTitle;
            }
            rs = k.replace("\\/", "/");
        } catch (Exception e) {
            return oldTitle;
        }

        return rs;
    }
    protected static final int max = 100;
    protected static final String HILIGNT_TAG_S = UUID.randomUUID().toString();
    protected static final String HILIGNT_TAG_E = UUID.randomUUID().toString();
    protected static final String SPAN_S = "<span class=\"keywordHighLight\">";
    protected static final String SPAN_E = "</span>";
    protected void setHighLighter(SolrQuery solrQuery, ArticleSolrQuery query) {
        solrQuery.setHighlight(true);
        /*
         * hl.usePhraseHighlighter: 如果一个查询中含有短语（引号框起来的）那么会保证一定要完全匹配短语的才会被高亮。 默认值：true
         */
        solrQuery.setParam("hl.usePhraseHighlighter", false);
        solrQuery.setParam("hl.fragsize", String.valueOf(max));
        solrQuery.setParam("hl.bs.chars", ".,!?\t\n，。！？<>");
        solrQuery.setParam("hl.boundaryScanner", "breakIterator");
//        solrQuery.setHighlightFragsize(600);
        solrQuery.addHighlightField(ArticleField.articleTitle);
        solrQuery.addHighlightField(ArticleField.articleContent);
        // 以下两个方法主要是在高亮的关键字前后加上html代码
        String tag = query.getHilightTag();
        if(StringUtils.isBlank(tag) || tag.equalsIgnoreCase("span")) {
            //keywordHighLight
            solrQuery.setHighlightSimplePre(HILIGNT_TAG_S);
            solrQuery.setHighlightSimplePost(HILIGNT_TAG_E);
        } else {
            solrQuery.setHighlightSimplePre(tag + "S");
            solrQuery.setHighlightSimplePost(tag + "E");
        }

    }
}
